<template>
  <div class="product-detail">
    <!-- 头部区域 -->
    <!-- <header class="detail-nav">
      <i class="iconfont iconfont-31fanhui1" @click="gohome"></i>
      <div class="nav-list">
        <span class="active">
          <i class="iconfont iconfont-zuobiao"></i>
          商品
        </span>
        <span>商品详情</span>
        <span>商品推荐</span>
      </div>
      <i class="iconfont icon-gengduo"></i>
    </header> -->
    <z-header>
      <template v-slot:search>
        <div class="nav-list">
          <span :class="{ active: navIndex === 0 }" @click="navSelectItem(0)">
            <i
              :class="{ iconfont: true, 'iconfont-zuobiao': navIndex === 0 }"
            ></i
            >商品
          </span>
          <span :class="{ active: navIndex === 1 }" @click="navSelectItem(1)">
            <i
              :class="{ iconfont: true, 'iconfont-zuobiao': navIndex === 1 }"
            ></i
            >商品详情
          </span>
          <span :class="{ active: navIndex === 2 }" @click="navSelectItem(2)">
            <i
              :class="{ iconfont: true, 'iconfont-zuobiao': navIndex === 2 }"
            ></i
            >商品推荐
          </span>
        </div>
      </template>
    </z-header>
    <!-- 轮播 -->
    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item v-for="(item, index) in subImagesList" :key="index"
        ><img :src="item.imgUrl" alt=""
      /></van-swipe-item>
    </van-swipe>
    <!-- 详情信息 -->
    <div class="detail-info">
      <p class="detail-info-name">{{ productDetail.name }}</p>
      <p class="detail-info-subtitle">{{ productDetail.subtitle }}</p>
      <div class="detail-num">
        <span class="detail-info-price">￥{{ productDetail.price }}</span>
        <span class="detail-info-stock">库存 {{ productDetail.stock }} 件</span>
      </div>
    </div>
    <!-- 详情详情 -->
    <div class="detail-content" ref="detailContent" id="content">
      <p class="detail-gap"></p>
      <ul class="introduce">
        <li>概述</li>
        <li>参数</li>
        <li>安装服务</li>
        <li>常见问题</li>
      </ul>
      <div v-html="productDetail.detail" class="imgdata"></div>
    </div>
    <!-- 加入购物车组件 -->
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" color="#ee0a24" />
      <van-goods-action-icon icon="cart-o" text="购物车" />
      <van-goods-action-button
        type="warning"
        text="加入购物车"
        @click="handShopCart"
      />
      <van-goods-action-button
        type="danger"
        text="立即购买"
        @click="handShopCart"
      />
    </van-goods-action>
    <van-sku
      v-model="show"
      :sku="sku"
      :goods="goods"
      :goods-id="goodsId"
      :hide-stock="sku.hide_stock"
      @buy-clicked="onBuyClicked"
      @add-cart="onAddCartClicked"
    />
  </div>
</template>

<script>
import { cartAdd, getProductDetail } from "../../api/api";
import zHeader from "../../components/common/z-header.vue";
export default {
  components: { zHeader },
  data() {
    return {
      navIndex: 0,
      id: this.$route.params.id,
      // 轮播图图片
      subImagesList: [],
      // 详细信息
      productDetail: {},
      // 详情展示图片
      detailImgs: [],
      show: false,
      sku: {
        tree: [
          {
            k: "颜色",
            v: [
              {
                id: "1",
                name: "红色",
                imgUrl:
                  "http://img.happymmall.com/570186f3-c0d2-4336-a1b7-3e1aff88f73a.jpg",
                previewImgUrl:
                  "http://img.happymmall.com/570186f3-c0d2-4336-a1b7-3e1aff88f73a.jpg",
              },
              {
                id: "1",
                name: "蓝色",
                imgUrl:
                  "http://img.happymmall.com/a73b6326-1204-4937-aa88-097c9eda8a2a.jpg",
                previewImgUrl:
                  "http://img.happymmall.com/a73b6326-1204-4937-aa88-097c9eda8a2a.jpg",
              },
            ],
            k_s: "s1",
          },
        ],
        list: [
          {
            id: 2259, // skuId，下单时后端需要
            price: 100, // 价格（单位分）
            s1: "1", // 规格类目 k_s 为 s1 的对应规格值 id
            s2: "1",
            stock_num: 110, // 当前 sku 组合对应的库存
          },
        ],
        price: "1.00",
        stock_num: 227,
        collection_id: 2261,
        none_sku: false,
        hide_stock: false,
      },
      // 缩略图
      goods: {
        picture:
          "http://img.happymmall.com/570186f3-c0d2-4336-a1b7-3e1aff88f73a.jpg",
      },
      // 商品id
      goodsId: 2261,
    };
  },
  methods: {
    // 定位 导航切换
    navSelectItem(index) {
      this.navIndex = index;
      switch (index) {
        case 0:
          window.scroll(0, 0);
          break;
        case 1:
          window.scroll(0, this.$refs.detailContent.offsetTop - 50);
          break;
        default:
          break;
      }
    },
    // 立即购买 检测 用户是否登录
    handShopCart() {
      if (!this.$store.getters.getIsLogin) {
        this.$dialog
          .confirm({
            closeOnClickOverlay: true,
            title: "提示",
            message: "请登录！",
          })
          .then(() => {
            this.$router.push("/login");
          })
          .catch(() => {
            console.log("关闭弹窗");
          });
        return;
      }
      this.show = true;
    },
    gohome() {
      this.$router.go(-1);
    },
    findDetailData() {
      const params = {
        id: this.id,
      };
      getProductDetail(params, (res) => {
        this.productDetail = res.data;
        let subImages = res.data.subImages.split(",");
        let imageHost = res.data.imageHost;
        subImages.forEach((item) => {
          this.subImagesList.push({
            imgUrl: imageHost + item,
          });
        });

        // 组装详情展示图片
        const re = /(\/\/\S+(\.jpg|\.png|\.jpeg|\.webp))/g;
        let tempDetalImgs = [];
        this.productDetail.detail.replace(re, (substr) => {
          tempDetalImgs.push(substr);
        });
        this.detailImgs = tempDetalImgs;

        // 组装 SKU 数据
        this.setSku(this.productDetail, this.subImagesList);
      });
    },
    // 购买
    onBuyClicked() {
      console.log("购买");
    },
    // 添加商品
    onAddCartClicked(value) {
      const params = {
        productId: value.goodsId,
        count: value.selectedNum,
      };
      
      // 添加到 购物车
      cartAdd(params, (res) => {
        if (res.status === 0) {
          this.$router.push("/shopcart");
        } else {
          this.$toast.fail("添加购物车失败！");
        }
      });

      this.show = true;
    },
    // 组装 SKU 数据
    setSku(productDetail, subImagesList) {
      let tempTreeV = [];
      this.sku.list = [];
      for (let index = 0; index < 2; index++) {
        // 组装 suk.tree[0].v
        let obj = {
          id: index + 1,
          name: "红色",
          imgUrl: subImagesList[index].imgUrl,
          previewImgUrl: subImagesList[index].imgUrl,
        };
        if (index === 1) {
          obj.name = "蓝色";
        }
        tempTreeV.push(obj);

        // 组装 sku.list
        let preItem = {
          id: productDetail.id,
          s1: index + 1,
          price: productDetail.price * 100,
          stock_num: productDetail.stock - 1,
        };
        // console.log('123',preItem);
        if (index === 1) {
          preItem.stock_num = 1;
        }

        this.sku.list.push(preItem);
      }
      this.sku.tree[0].v = tempTreeV;

      // 价格 和库存总数
      this.sku.price = this.productDetail.price; // 默认价格（单位元）
      this.sku.stock_num = this.productDetail.stock - 0; // 商品总库存

      // 商品展示的默认图
      this.goods.picture = subImagesList[0].imgUrl;

      // 设置 对应商品ID
      this.goodsId = productDetail.id;
      // console.log("id", this.goodsId);
    },
  },
  created() {
    this.findDetailData();
  },
};
</script>

<style lang="scss" scoped>
.detail-nav {
  position: fixed;
  left: 0;
  top: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 72px;
  padding: 0 21px;
  z-index: 10;
  box-sizing: border-box;
  background: #fff;

  .iconfont {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 36px;
    height: 100%;
    font-size: 25px;

    &::before {
      width: 28px;
      height: 28px;
    }
  }

  .iconfont-zuobiao {
    height: 100%;
    display: inline-block;
  }
}

.nav-list {
  display: flex;
  align-items: center;
  width: 70%;
  height: 100%;

  span {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    flex: 1;
    text-align: center;
  }

  .active {
    color: #f63515;
  }
}

.my-swipe .van-swipe-item {
  height: 504px;
  color: #fff;
  font-size: 20px;
  line-height: 150px;
  text-align: center;
  margin-top: 72px;
  background-color: #39a9ed;

  img {
    width: 100%;
    height: 100%;
  }
}

.detail-info {
  width: 100%;
  padding: 14px 21px;
  box-sizing: border-box;

  .detail-info-name {
    color: #333;
    font-size: 28px;
  }

  .detail-info-subtitle {
    padding: 7px 0;
    font-size: 20px;
    color: #999;
  }

  .detail-num {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 31px;
    color: #999;

    .detail-info-price {
      color: #f63515;
    }

    .detail-info-stock {
      font-size: 23px;
    }
  }
}

.detail-content {
  .detail-gap {
    height: 14px;
    background: #eee;
  }

  .introduce {
    display: flex;
    justify-content: space-between;
    margin: 14px 0;

    li {
      flex: 1;
      padding: 7px 0;
      font-size: 21px;
      text-align: center;
      border-right: 1px solid #999;
    }

    li:nth-child(4) {
      border: none;
    }
  }

  .imgdata {
    width: 100%;

    // 样式穿透
    ::v-deep p {
      width: 100%;
      text-align: center;

      img {
        width: 100%;
        height: 100%;
        vertical-align: top;
      }
    }
  }
}
</style>